import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges } from '@angular/core';
import { subHours } from 'date-fns';
import { TimeRangeService } from './time-range.service';

interface ValueOption {
    key: string;
    startTime?: any;
    endTime?: any;
    lineBreak?: boolean;
    cssClass?: string;
}

/** 时间区间组件
 * 使用说明：<app-datetime-picker (valueChange)="dateChange($event)" [dateTimeOptions]="dateTimeOptions"></app-datetime-picker>
 * valueChange: 事件传入的参数为{startTime: Date类型, endTime: Date类型, key: "last_24_hours"}，
 *              其中startTime为开始时间，endtime为结束时间，key为时间模式
 * dateTimeOptions：初始时间,初始配置 { startTime: Date类型, endTime: Date类型, key: "custom", lineBreak: true/false}
 *              lineBreak时间展示换行处理与否，默认换行(false)
 *              cssClass: 组件的css全局类，has-border: 表示有边框
 * clearTimeMode: 是否展示清除设置
 * layoutMode: 布局模式, 默认为'standard': 标准模式, 还支持'vertical': 水平模式
 */

@Component({
    selector: 'app-datetime-picker',
    templateUrl: './datetime-picker.component.html',
    styleUrls: ['./datetime-picker.component.styl'],
    providers: [
        TimeRangeService
    ],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class DatetimePickerComponent implements OnInit, OnChanges {

    @Output() valueChange = new EventEmitter();
    @Input() dateTimeOptions: ValueOption; // 时间模式
    @Input() clearTimeMode = true;
    @Input() layoutMode = 'standard';

    // 快捷模式选项
    @Input() quickModeOptions = ['last_1_hour', 'last_24_hours','last_1_day', 'last_7_days', 'last_30_days'];
    // 时间模式含义映射
    dateTimeOptionsMap = {
        'last_1_hour': '1小时',
        'today': '今天',
        'last_24_hours': '24小时',
        'last_3_days': '3天',
        'last_7_days': '7天',
        'last_30_days': '30天',
        'last_1_day':'1天',
        'custom': '自定义',
        'clear_time': '清除时间'
    };
    customPanelIsShow = false;
    mainPanelIsShow = false;
    // 提交时间
    startDate: Date = null;
    endDate: Date = null;

    // 自定义时间
    customStartDate: Date = null;
    customEndDate: Date = null;

    timeRange: any;
    // 时间对象范围
    dateRange = [null, null];

    constructor(
        private timeRangeService: TimeRangeService
    ) {
        // 获取时间区间对应的开始时间和结束时间
        this.timeRange = this.timeRangeService.getTimeRange();
    }

    showMainPanel() {
        this.mainPanelIsShow = !this.mainPanelIsShow;
        this.customPanelIsShow = this.dateTimeOptions.key === 'custom';
    }

    hideMainPanel() {
        this.mainPanelIsShow = false;
        this.customPanelIsShow = false;
    }

    showCustomPanel() {
        this.customPanelIsShow = true;
    }

    hideCustomPanel() {
        this.customPanelIsShow = false;
    }

    // 自定义模式
    disabledEndDate = (endDate: Date): boolean => {
        if (!endDate || !this.startDate) {
            return false;
        }
        return endDate.getTime() <= this.customStartDate.getTime();
    };

    disabledStartDate = (startDate: Date): boolean => {
        if (!startDate || !this.endDate) {
            return false;
        }
        return startDate.getTime() >= this.customEndDate.getTime();
    }

    onStartChange(date: Date): void {
        this.customStartDate = date;
    }

    onEndChange(date: Date): void {
        this.customEndDate = date;
    }

    /**
     * 初始化组件
     * @param value：string类型，为'custom'时，必须设置开始时间和结束时间
     * }
     */
    initOptions(value: string, type?) {
        if (value !== 'custom') {
            this.hideMainPanel();
            const date = this.getTimeRange(value);
            this.startDate = date.startTime;
            this.endDate = date.endTime;
            this.valueChange.emit({
                startTime: this.startDate,
                endTime: this.endDate,
                key: value
            });
        } else {
            if (type) {
                // 初始选择自定义时间，默认为最近一小时
                this.customStartDate = this.dateTimeOptions.startTime || subHours(new Date(), 1);
                this.customEndDate = this.dateTimeOptions.endTime || new Date();
                this.customConfirm(type);
            } else {
                // 从面板选择自定义时间，默认不发生请求，显示的开始结束时间为startDate和endDate
                this.customStartDate = this.cloneDate(this.startDate) || subHours(new Date(), 1);
                this.customEndDate = this.cloneDate(this.endDate) || new Date();
            }
        }
    }

    cloneDate(date: Date) {
        return date ? new Date(date.valueOf()): null;
    }

    customConfirm(type?) {
        this.startDate = this.cloneDate(this.customStartDate);
        this.endDate = this.cloneDate(this.customEndDate);
        this.valueChange.emit({
            startTime: this.startDate,
            endTime: this.endDate,
            key: 'custom'
        });

        if (type === 'hide') {
            // 初始选择自定义时间，关闭面板
            this.hideMainPanel();
        }
    }

    resetCustom() {
        this.customStartDate = this.cloneDate(this.startDate);
        this.customEndDate = this.cloneDate(this.endDate);
    }

    /**
     * 非自定义时间
     * @param index: 区间标签
     */
    getTimeRange(index: string) {
        let date = {startTime: null, endTime: null};
        this.timeRange = this.timeRangeService.getTimeRange();
        switch (index) {
            case 'last_30_days':
                date = this.timeRange.last_30_days;
                break;
            case 'last_24_hours':
                date = this.timeRange.last_24_hours;
                break;
            case 'last_1_day':
                date = this.timeRange.last_1_day;
                break;
            case 'last_3_days':
                date = this.timeRange.last_3_days;
                break;
            case 'last_7_days':
                date = this.timeRange.last_7_days;
                break;
            case 'today':
                date = this.timeRange.today;
                break;
            case 'last_1_hour':
                date = this.timeRange.last_1_hour;
                break;
            case 'clear_time':
                date.startTime = null;
                date.endTime = null;
                break;
            default:
                this.dateTimeOptions.key = 'custom';
                date = this.timeRange.last_1_hour;
                break;

        }
        return date;
    }

    /**
     * 快速模式切换触发事件
     * @param mode: 时间模式
     */
    changeMode(mode: string) {
        this.dateTimeOptions.key = mode;
        const date = this.getTimeRange(mode);
        this.startDate = date.startTime;
        this.endDate = date.endTime;
        this.dateRange = [this.startDate, this.endDate];
        this.valueChange.emit({
            startTime: this.startDate,
            endTime: this.endDate,
            key: mode
        });
    }

    /**
     * 时间范围确定按钮的回调
     */
    timeSubmit() {
        this.dateTimeOptions.key = 'custom';
        this.valueChange.emit({
            startTime: this.dateRange[0],
            endTime: this.dateRange[1],
            key: 'custom'
        });
    }

    ngOnInit() {
        if (this.layoutMode === 'standard') {
            // 初始化执行默认时间模式
            if (!this.dateTimeOptions) {
                // 默认最近一小时
                this.dateTimeOptions = {
                    key: 'custom',
                    ...this.timeRange.last_1_hour
                };
            }
            this.initOptions(this.dateTimeOptions.key, 'hide');
        } else if (this.layoutMode === 'vertical') {
            this.changeMode(this.dateTimeOptions.key);
        }
    }

    ngOnChanges(changes: SimpleChanges) {
        const dateTimeChanges = changes['dateTimeOptions'];
        if (!dateTimeChanges.firstChange) {
            if (this.dateTimeOptions && this.dateTimeOptions.key) {
                this.initOptions(this.dateTimeOptions.key, 'hide');
            }
        }
    }
}
